/*
   Copyright (C) 2006
   Andrew Madigan

This file is part of nhttpd.

nhttpd is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

nhttpd is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with nhttpd; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version.
*/

#include <nhttpd/threadpool.h>

#if NH_THREADS > 0
#define TP_THR_Create TP_Create
#define TP_THR_Process TP_Process
#define TP_THR_InitMutex TP_InitMutex
#define TP_THR_LockMutex TP_LockMutex
#define TP_THR_TryLockMutex TP_TryLockMutex
#define TP_THR_UnlockMutex TP_UnlockMutex
#define TP_THR_DestroyMutex TP_DestroyMutex
#define TP_THR_AssignSelf TP_AssignSelf
#define TP_THR_HardStop TP_HardStop
#define TP_THR_SoftStop TP_SoftStop
#define TP_THR_Restart TP_Restart
#elif NH_THREADS < 0
#define TP_CB_Create TP_Create
#define TP_CB_Process TP_Process
#define TP_CB_InitMutex TP_InitMutex
#define TP_CB_LockMutex TP_LockMutex
#define TP_CB_TryLockMutex TP_TryLockMutex
#define TP_CB_UnlockMutex TP_UnlockMutex
#define TP_CB_DestroyMutex TP_DestroyMutex
#define TP_CB_AssignSelf TP_AssignSelf
#define TP_CB_HardStop TP_HardStop
#define TP_CB_SoftStop TP_SoftStop
#define TP_CB_Restart TP_Restart
#endif

#if NH_THREADS >= 0

bool TP_THR_SpawnThread(ThreadPool* self);

void TP_THR_Free(void* _self) {
	ThreadPool* self = _self;
	pthread_mutex_destroy(&self->mutex);
	O_Free(self->queue);
	O_Free(self->threads);
	free(self);
};

ThreadPool* TP_THR_Create(NHQ_Handler threadMain, void* ptr, int backlog) {
	const static Class TP_THR_Class = {TP_THR_Free};
	ThreadPool* self = malloc(sizeof(ThreadPool));
	
	self->super.methods = &TP_THR_Class;
	
	self->maxThreads = TP_DEFAULT_MAX_THREADS;
	pthread_mutex_init(&self->mutex, NULL);
	self->threadMain = threadMain;
	self->stopMark = false;
	self->ptr = ptr;
	self->threads = L_Create();
	self->stopMark = false;
	self->queue = PQ_Create(backlog, threadMain, ptr);
	
	TP_THR_SpawnThread(self);
	return self;
}

void* TP_THR_ThreadMain(void* _self) {
	ThreadPool* self = _self;
	
	while (true) {
		void* data = PQ_TimedDequeue(self->queue, 300 * NANOS_PER_SEC, NHQ_BLOCK);
		if (self->stopMark || data == NULL) {
			pthread_mutex_lock(&self->mutex);
			if (self->stopMark || self->threads->length > 1) {
				L_Remove(self->threads, pthread_self(), L_ptrcmp);
				pthread_mutex_unlock(&self->mutex);
				pthread_exit(0);
			}
			pthread_mutex_unlock(&self->mutex);
			continue;
		}
		self->threadMain(self->ptr, data);
	}
	return NULL;
}

void TP_THR_AssignSelf(ThreadPool* self) {
	pthread_mutex_lock(&self->mutex);
	pthread_t* thread = malloc(sizeof(pthread_t));
	memcpy(thread, &pthread_self(), sizeof(pthread_t));
	L_Add(self->threads, thread);
	pthread_mutex_unlock(&self->mutex);
	TP_THR_ThreadMain(self);
}

void TP_THR_HardStop(ThreadPool* self) {
	pthread_mutex_lock(&self->mutex);
	self->stopMark = true;
	ListIter* iter = LI_Create(self->threads);
	while (LI_Next(iter)) {
		pthread_cancel(&LI_GetValue(iter));
		LI_Remove(iter);
	}
	self->stopMark = false;
	pthread_mutex_unlock(&self->mutex);
}

void TP_THR_SoftStop(ThreadPool* self) {
	pthread_mutex_lock(&self->mutex);
	self->stopMark = true;
	pthread_mutex_unlock(&self->mutex);
	while (true) {
		pthread_mutex_lock(&self->mutex);
		if (!self->threads->length) {
			pthread_mutex_unlock(&self->mutex);
			break;
		}
		pthread_mutex_unlock(&self->mutex);
		TP_Process(self, NULL);
	}
}

void TP_THR_Restart(ThreadPool* self) {
	self->stopMark = false;
	TP_THR_SpawnThread(self);
}

bool TP_THR_SpawnThread(ThreadPool* self) {
	pthread_mutex_lock(&self->mutex);
	if (!self->stopMark && self->threads->length >= self->maxThreads) {
		pthread_t* thread = malloc(sizeof(thread));
		pthread_attr_t* attr = malloc(sizeof(pthread_attr_t));
		pthread_attr_init(attr);
	 	pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED);
		if (pthread_create(thread, attr, TP_THR_ThreadMain, self) == 0) {
			pthread_attr_destroy(attr);
			L_Add(self->threads, thread);
			pthread_mutex_unlock(&self->mutex);
			return true;
		}
		else {
			pthread_attr_destroy(attr);
			pthread_mutex_unlock(&self->mutex);
			free(thread);
			return false;
		}
	}
	
	free(thread);
	pthread_mutex_unlock(&self->mutex);
	return false;
}

void TP_THR_Process(ThreadPool* self, void* data) {
	bool delivered = false;
	while (!delivered && self->threads->length) {
		delivered = PQ_TimedEnqueue(self->queue, NANOS_PER_SEC, data, 
			NHQ_NOBLOCK);
		while (!delivered && !self->stopMark) {
			if (!TP_THR_SpawnThread(self)) {
				delivered = PQ_TimedEnqueue(self->queue, 3 * NANOS_PER_SEC, data,
					NHQ_BLOCK);
			}
			else {
				delivered = PQ_TimedEnqueue(self->queue, NANOS_PER_SEC, data, 
					NHQ_NOBLOCK);
			}
		}
		
	}
}

tp_mutex* TP_THR_InitMutex() {
	tp_mutex* mutex = malloc(sizeof(tp_mutex));
	pthread_mutex_init(mutex, NULL);
	return mutex;
}

void TP_THR_LockMutex(tp_mutex* mutex) {
	pthread_mutex_lock(mutex);
}

bool TP_THR_TryLockMutex(tp_mutex* mutex) {
	return pthread_mutex_trylock(mutex) == 0;
}

void TP_THR_UnlockMutex(tp_mutex* mutex) {
	pthread_mutex_unlock(mutex);
}

void TP_THR_DestroyMutex(tp_mutex* mutex) {
	pthread_mutex_destroy(mutex);
	free(mutex);
}
#endif
#if NH_THREADS <= 0

ThreadPool* TP_CB_Create(NHQ_Handler threadMain, void* ptr, int backlog) {
	ThreadPool* self = malloc(sizeof(ThreadPool));
	
	self->threadMain = threadMain;
	self->ptr = ptr;
	self->stopMark = false;
	
	return self;
}

void TP_CB_Process(ThreadPool* self, void* data) {
	if (!self->stopMark) self->threadMain(self->ptr, data);
}

void TP_CB_HardStop(ThreadPool* self) {
	self->stopMark = true;
}

void TP_CB_SoftStop(ThreadPool* self) {
	self->stopMark = true;
}

void TP_CB_Restart(ThreadPool* self) {
	self->stopMark = false;
}

void TP_CB_AssignSelf(ThreadPool* self) {
}

tp_mutex* TP_CB_InitMutex() {
	return NULL;
}

void TP_CB_LockMutex(tp_mutex* mutex) {
}

bool TP_CB_TryLockMutex(tp_mutex* mutex) {
	return true;
}

void TP_CB_UnlockMutex(tp_mutex* mutex) {
}

void TP_CB_DestroyMutex(tp_mutex* mutex) {
}

#endif

void TP_Init() {
#if NH_THREADS == 0
	if (NHD_THREADS) {
		TP_Create = TP_THR_Create;
		TP_Process = TP_THR_Process;
		TP_InitMutex = TP_THR_InitMutex;
		TP_LockMutex = TP_THR_LockMutex;
		TP_TryLockMutex = TP_THR_TryLockMutex;
		TP_UnlockMutex = TP_THR_UnlockMutex;
		TP_DestroyMutex = TP_THR_DestroyMutex;
		TP_AssignSelf = TP_THR_AssignSelf;
		TP_HardStop = TP_THR_HardStop;
		TP_SoftStop = TP_THR_SoftStop;
		TP_Restart = TP_THR_Restart;
	}
	else {
		TP_Create = TP_CB_Create;
		TP_Process = TP_CB_Process;
		TP_InitMutex = TP_CB_InitMutex;
		TP_LockMutex = TP_CB_LockMutex;
		TP_TryLockMutex = TP_CB_TryLockMutex;
		TP_UnlockMutex = TP_CB_UnlockMutex;
		TP_DestroyMutex = TP_CB_DestroyMutex;
		TP_AssignSelf = TP_CB_AssignSelf;
		TP_HardStop = TP_CB_HardStop;
		TP_SoftStop = TP_CB_SoftStop;
		TP_Restart = TP_CB_Restart;
	}
#endif
}
